package com.product.timeTask;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description: MysqldumpService
 * 数据库定时备份service
 * @date: 2021/3/25
 * @author: 王瑾
 */
@Slf4j
@Component
public class Mysqldump {

    @Value("${spring.datasource.backupPath}")
    private String backupPath;

    @Value("${spring.datasource.dbName}")
    private String dbName;

    @Value("${spring.datasource.username}")
    private String name;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.ip}")
    private String ip;

    @Value("${spring.datasource.port}")
    private String port;

    @Value("${spring.datasource.mysqlpath}")
    private String mysqlPath;

    @PostConstruct
    @Scheduled(cron = "0 0 2 * * ?")  // 每俩个小时执行
    public void databaseBackup() {
        //定时执行的方法 , 定时进行数据库备份
        log.info("================数据库备份开始====================");
        mysqldump(backupPath,dbName,ip,port,name,password,mysqlPath);
        log.info("================数据库备份结束====================");
    }

    /**
     *  mysql数据库备份方法
     * @param backupPath  备份文件存放目录
     * @param dbName  数据库名称 (如有多个自行修改添加)
     * @param ip      数据库主机ip
     * @param port    数据库端口
     * @param name    用户
     * @param password  密码
     * @param mysqlPath   mysql安装bin目录
     */
    public void  mysqldump(String backupPath,String dbName,String ip,String port,String name,String password,String mysqlPath){
//        1,判断备份文件目录是否存在
        File file = new File(backupPath);
        if(!file.exists()){
            file.mkdir();
        }
//        2, 创建需要保存的文件
        String dateTime = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        log.info("生成文件名称：" + file + File.separator + dateTime + "-" + dbName + ".sql");
//        File.separator  文件路径分隔符
        File dataFile = new File(file + File.separator + dateTime + "-" + dbName + ".sql");
        if(dataFile.exists()){
            log.info("文件名已存在");
            return;
        }
//   3, 进行数据库备份
        try {
//            3.1 获取cmd并执行备份语句
            String smtp = mysqlPath + "mysqldump -h"+ip+"  -P"+port +
                    "  -u"+name+"  --password="+password+"   "+dbName+"  >  " + dataFile;
            String[] comment = {"cmd","/c",smtp};
            log.info(smtp);
            Process exec = Runtime.getRuntime().exec(comment);
//            3.2 如果有错误进行语句输出查看
            InputStream errorStream = exec.getErrorStream();
            log.info(IOUtils.toString(errorStream,"UTF-8"));
//            3.3 判断数据库是否备份完毕
            if(exec.waitFor() == 0){
                log.info("数据库备份完毕,路径为:  "+dataFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}